// 子表新增行逻辑

import deepCopy from '../../../../public/functions/deep-copy';
import addSubTableRow from '../../request-functions/addSubTableRow';

export default async function (tableId, index, values = {}, focus = false) {
    const {
        cardTable: {
            addRow,
            getAllRows,
            setEditableByIndex,
            getCurrentIndex
        },
        form: {
            getAllFormValue
        }
    } = this.props;

    const {
        humanResourceOrganizationValue: {
            refpk
        }
    } = this.state;

    let formData = deepCopy(getAllFormValue('hi_psnjob_h'));
    let tableData = deepCopy(getAllRows(tableId));

    let postData = {
        func_type: '1',
        pk_org: refpk,
        psnjobForm: formData,
        table_code: tableId,
        trialRow: []
    };

    if (tableId === 'hi_psndoc_trial') {

        let lastTrial = tableData.pop();
        if (!lastTrial) {
            postData['trialRow'] = null;
        } else {
            let trialRow = {};
            trialRow.areacode = 'hi_psndoc_trial';
            trialRow.rows = [];
            trialRow.rows[0] = lastTrial;
            postData['trialRow'] = trialRow;
        }

    }

    try {
        let res = await addSubTableRow(postData);
        if (res.success) {
            let newRowData = res.data.grid ?
                res.data.grid[tableId].rows[0].values :
                res.data[tableId].rows[0].values;

            if (tableId === 'hi_psndoc_ctrt') {
                let isCtrtEditable = res.data.isCtrtEditable
                addRow(tableId, index, newRowData, true);
                let currentIndex = getCurrentIndex(tableId)
                // true为可编辑
                setEditableByIndex(tableId, currentIndex, 'contractnum', isCtrtEditable)
                let contartNewCodeList = this.state.contartNewCodeList;
                newRowData.contractnum.value && contartNewCodeList.push(newRowData.contractnum.value)
                this.setState({contartNewCodeList: contartNewCodeList})
            } else {
                addRow(tableId, index, newRowData, focus);
            }
        }
    } catch (e) {
    }
}
